//
//  SinaOauthViewController.swift
//  weibo
//
//  Created by sirius on 16/1/3.
//  Copyright © 2016年 sirius. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class SinaOauthViewController: UIViewController,UIWebViewDelegate{
    
    let webView = UIWebView()
    override func loadView() {
        // 设置web 页面为视图
       
        view = webView
        setupNav()
        
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // 跳转页面时，设置背景颜色

        view.backgroundColor = UIColor.redColor()
        // 1.1 加载授权页面
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=4115747165&redirect_uri=http://www.baidu.com")
        // 1.2 创建一个请求，url可以强制解包（url写死）
        let request = NSURLRequest(URL: url!)
        // 1.3 加载
        webView.loadRequest(request)
        //设置代理
        webView.delegate = self
    }
}
    //MARK:--导航控制器
    extension SinaOauthViewController{
    private func setupNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Auto填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
    }
    
    //MARK: --按钮的实现方法
    //document.getElementById('userId').value = "2222"
    @objc private func dismiss(){
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    func autofill(){
        // 1 js -- \是转义字符
        let js = "document.getElementById('userId').value = \"13161858164\";document.getElementById('passwd').value = \"1450kk\""
        // 2 让web页面加载 js,
        webView.stringByEvaluatingJavaScriptFromString(js)

}
}
   //MARK:--页面的代理方法,加载忙的试图
    extension SinaOauthViewController {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}
   //MARK:----进行网络请求，返回true,让web加载，返回false 进行拦截Code
    extension SinaOauthViewController{
    //进行网络请求，返回true,让web加载，返回false 进行拦截
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //        printLog(request.URL?.absoluteString)
        if let url = request.URL?.absoluteString {
            if url.hasPrefix(redirect_url){
                printLog(url)
                //截取code
                if let code = request.URL?.query{
                    let subStr = code.substringFromIndex("code=".endIndex)
                    printLog(subStr)
//                    let accountModel = SinaAccountViewModel()
                SinaAccountViewModel.shareInstance.getToken(subStr, success: { () -> () in
                    printLog("成功")
                    NSNotificationCenter.defaultCenter().postNotificationName(kNotificationEnter, object: self)
                    }, failure: { (error) -> () in
                        printLog("error")
                        
                        
                   })
                }
                return false
            }
            
        }
        return true
    }
}

    
    //MARK:--通过Token,来获取用户信息
extension SinaOauthViewController{
    //参数uid与screen_name二者必选其一，且只能选其一；
     }

/*
http://www.baidu.com/?code=c45a85f6ed38f6635d07bdd3b6d68eda
*/
/*
webView(_:shouldStartLoadWithRequest:navigationType:): Optional("https://api.weibo.com/oauth2/authorize?client_id=4115747165&redirect_uri=http://www.baidu.com")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("https://api.weibo.com/oauth2/authorize")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("https://api.weibo.com/oauth2/authorize#")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("https://api.weibo.com/oauth2/authorize")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("http://www.baidu.com/?code=a18f48ca1d3c16ab67c1b35b31f81d57")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("https://m.baidu.com/?code=a18f48ca1d3c16ab67c1b35b31f81d57&from=844b&vit=fps")
SinaOauthViewController.swift[68], webView(_:shouldStartLoadWithRequest:navigationType:): Optional("about:blank")


*/
